package com.roger.myHome.component;

import com.google.gson.Gson;
import com.roger.myHome.aspect.WebLog;
import com.roger.myHome.es.entity.LogInfo;
import com.roger.myHome.util.DateUtil;
import com.roger.myHome.util.StringUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect  // 表明此类为一个切面
@Component  // 随着框架的启动而启动
@Slf4j
@AllArgsConstructor
public class WebLogAspect {
    /**
     * 以自定义 @WebLog 注解为切点
     */
    @Pointcut("@annotation(com.roger.myHome.aspect.WebLog)")
    public void webLog() {
    }

    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 获取 @WebLog 注解的描述信息
        String methodDescription = getAspectLogDescription(joinPoint);

        // 打印请求相关参数
        LogInfo logInfo = new LogInfo();
        //logInfo.setId(UUIDs.base64UUID().toLowerCase());
        logInfo.setUrl(request.getRequestURL().toString());
        logInfo.setDes(methodDescription);
        logInfo.setHttpMethod(request.getMethod());
        logInfo.setClassMethod(joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logInfo.setIp(request.getRemoteAddr());
        logInfo.setRequestArgs(joinPoint + "");
        logInfo.setLogTime(DateUtil.getCurrentTime());
        logInfo.setTimestamps(System.currentTimeMillis());
        log.info("请求相关参数:[{}]",logInfo);
    }

    /**
     * 环绕
     *
     * @param proceedingJoinPoint
     * @return java.lang.Object
     * @throws Throwable
     * @author 卡尔
     * @date 2021/10/13 11:49
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        log.info("返回数据:[{}]", new Gson().toJson(result));
        // 执行耗时
        log.info("耗时:[{}] ms", System.currentTimeMillis() - startTime);
        return result;
    }

    /**
     * 获取切面注解的描述
     *
     * @param joinPoint 切点
     * @return 描述信息
     * @throws Exception
     * @author 卡尔
     * @date 2021/10/13 11:48
     */
    public String getAspectLogDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        StringBuilder description = new StringBuilder();
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    String des = method.getAnnotation(WebLog.class).description();
                    String value = method.getAnnotation(WebLog.class).value();
                    if (!StringUtils.isNull(des)) {
                        description.append(des);
                    } else {
                        description.append(value);
                    }
                    break;
                }
            }
        }
        return description.toString();
    }
}

